//内部调拔结算（详情或者 新增)↓
<template>
  <!-- 集采汇总编辑页 -->
  <div class="e-form">
      <BillTop @cancel="handleClose"></BillTop>
    <!-- //详情 添加页面 ↓ -->
    <div class="tabs">
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="结算明细"
          name="planDetail"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <!-- <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane> -->
        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                    <el-form ref="rulesBase" :model="formData" :rules="rulesBase" label-width="150px" >
                        <el-row>
                            <el-col :span="12" >
                                <el-form-item label="结算编号：" prop="billNo">
                                    <span>{{formData.billNo}}</span>
                                    <!-- <el-input v-model="formData.billNo"></el-input> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="单据机构：" prop="orgName">
                                    <span>{{formData.orgName}}</span>
                                    <!-- <el-input v-model="formData.orgName"></el-input> -->
                                 </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="结算依据：">
                                    <span>物资调拔</span>
                                    <!-- <el-input v-model="formData.billNo"></el-input> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="源单编号：" prop="sourceBillNo">
                                    <span>
                                        {{formData.sourceBillNo}}
                                    </span>
                                    <span class="a"
                                    @click="goTocontract">查看</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="调入机构：" prop="transferInUnitName">
                                    <el-input v-model="formData.transferInUnitName" :disabled='true'></el-input>
                                    <el-button type="primary" @click="xzdbd">
                                    选择调拔单
                                    </el-button>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="结算日期：" prop="settlementDate">
                                     <el-date-picker
                                                v-model="formData.settlementDate"
                                                type="date"
                                                placeholder="请选择结算日期"
                                                value-format="yyyy-MM-dd"
                                                format="yyyy 年 MM 月 dd 日"
                                    ></el-date-picker>
                                 </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="税率%：" prop="taxRate">
                                    <el-input v-model="formData.taxRate" @change="isnumshow(formData.taxRate)"></el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="接收人员：" prop="receiverName">
                                    <span>{{formData.receiverName}}</span>
                                    <!-- <el-input v-model="formData.receiverName"></el-input> -->
                                            </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="税额(元)：" prop="taxAmoun">
                                    <!-- <span>{{formData.taxAmount}}</span>-->
                                    <el-input v-model="formData.taxAmount"></el-input>
                                    <!-- <span>{{shuie}}</span> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="税价合计(元)：">
                                    <!-- <span>{{formData.totalAmount}}</span>  -->
                                    <span>{{shuijiaheji}}</span>
                                    <!-- <el-input v-model="formData.totalAmount"></el-input> -->
                                            </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="结算金额(元)：">
                                    <!-- <span>{{formData.amount}}</span> -->
                                  <span>{{amount2}}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="本位币：">
                                    <span>{{formData.baseCurName}}</span>
                                    <!-- <el-input v-model="formData.baseCurName"></el-input> -->
                                            </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="调拔人员：">
                                    <span>{{formData.transferorName}}</span>
                                    <!-- <el-input v-model="formData.transferorName"></el-input> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                    <span>{{state.find(x=>x.value == formData.state)?state.find(x=>x.value == formData.state).label:''}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="币种：">
                                    <span>{{formData.currency}}</span>
                                    <!-- <el-input v-model="formData.currency"></el-input> -->
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="传财务共享：">
                                    <span :class="isFontColor ? 'redFont' : 'greenFont'">{{shareLable(formData.easId)}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币汇率：">
                                    <el-input v-model="formData.baseCurRate" :disabled="isReviseBaseCurRate"></el-input>
                                </el-form-item>
                            </el-col>
                             <el-col :span="12">
                                <el-form-item label="人名币汇率：">
                                    <span>{{formData.rmbRate}}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                        <el-row>
                                        <el-col :span="24">
                                            <el-form-item label="备注">
                                               <el-input type="textarea" :rows="2" laceholder="请输入内容" v-model="formData.remarks"></el-input>
                                            </el-form-item>
                                        </el-col>
                                    </el-row>

                    </el-form>
                </div>
              </div>
            </div>
          </div>

          <!-- 结算明细 -->
          <div id="planDetailCon" class="con">
            <div class="tabs-title" id="planDetail">结算明细</div>
            <div class="e-table">
                    <div class="top">
                      <div class="left">
                        <div>
                          <el-button
                            size="small"
                            style="background: rgb(75, 178, 255); color: #fff"
                            @click="xzdbd"
                            >新增</el-button
                          >
                          <el-button
                            size="small"
                            type="danger"
                            @click="shanchumx"
                            >删除</el-button
                          >
                        </div>
                      </div>
                    </div>
                       <!-- @cell-mouse-leave="cellMouseLeave" -->
                        <!-- @cell-mouse-enter="cellMouseEnter" -->
                        <!-- @cell-click="cellClick" -->
                        <!-- :row-class-name="tableRowClassNames" -->
                     <el-table
                        ref="wzmxtableTable"
                        :data="wzmxtable"
                        border
                        style="width: 100%; margin-top: 20px"
                        :cell-class-name="cellClsNm"
                        :header-cell-style="{ textAlign: 'center' }"
                        :cell-style="{ textAlign: 'center' }"
                        @selection-change="planTableSelect"
                        :row-class-name="tableRowClassName"
                        :tree-props="{
                            children: 'children',
                            hasChildren: 'hasChildren',
                        }"
                        row-key="uuid"
                        v-sortTable="{ 'tableData': wzmxtable, '_this': this, 'ref': 'wzmxtableTable' }"
                    >
                     <el-table-column type="selection" width="55">
                      </el-table-column>
                      <el-table-column prop="materialClassName" label="物资类别" width="150">
                      </el-table-column>
                      <el-table-column
                        prop="materialName"
                        label="物资名称"
                        min-width="120"
                      >
                      </el-table-column>
                      <el-table-column prop="spec" label="规格" width="100">
                      </el-table-column>
                      <el-table-column prop="texture" label="材质" width="100">
                      </el-table-column>
                      <el-table-column prop="unit" label="单位" width="100">
                      </el-table-column>
                      <el-table-column label="调拔数量" width="100">
                          <template slot-scope="{ row }">
                            {{ row.quantity}}
                            <!-- <el-input v-if="row.billId || row.billId == ''" type="number" v-model="row.amount"  @keyup.native="changnum('金额',row)"></el-input> -->
                          </template>
                      </el-table-column>
                      <el-table-column  label="未结算数量" width="100">
                          <template slot-scope="{ row }">
                            {{ row.unsettledQuantity}}
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>
                      <el-table-column  label="结算数量"  width="100">
                          <template slot-scope="{ row }">
                            <!-- {{ row.settledQuantity}} -->
                            <el-input v-model="row.jssl" v-if="row.billId || row.billId == ''"  @blur="mxchang(row,'jssl')"></el-input>
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>

                      <el-table-column  label="内部结算单价(元)" width="130">
                          <template slot-scope="{ row }">
                            {{ row.nbjsdj}}
                            <!-- <el-input v-model="row.nbjsdj" v-if="row.billId || row.billId == ''"></el-input> -->
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>

                      <el-table-column  label="实际采购单价(元)" width="130">
                          <template slot-scope="{ row }">
                            {{ row.actualPurchasePrice}}
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>

                      <el-table-column  label="结算金额(元)" width="100">
                          <template slot-scope="{ row }">
                            <!-- {{ row.name}} -->
                            <el-input v-model="row.jsje" v-if="row.billId || row.billId == ''" @blur="mxchang(row,'jsje')"></el-input>
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>

                        <el-table-column  label="价差(元)" width="100">
                          <template slot-scope="{ row }">
                            <!-- {{ row.name}} -->
                            <span  v-if="row.billId || row.billId == ''">{{row.difference}}</span>
                            <!-- <el-input v-model="row.difference" v-if="row.billId || row.billId == ''" @blur="mxchang(row,'jsje')"></el-input> -->
                            <!-- <el-input v-if="row.billId || row.billId == ''"  type="number" v-model="row.apportionmentRatio" @keyup.native="changnum('比例',row)" ></el-input> -->
                          </template>
                      </el-table-column>

                      <!-- <el-table-column  label="差价(元)" width="100">
                          <template slot-scope="{ row }">
                            {{ row.cj}}
                          </template>
                      </el-table-column> -->

                    </el-table>
                  </div>

          </div>

          <!-- 服务费用 -->
          <!-- <div id="fwfyCon" class="con">
                <div class="tabs-title" id="fwfy">服务费用</div>
          </div> -->

          <!-- 保证金 -->
          <!-- <div id="bzjCon" class="con">
            <div class="tabs-title" id="bzj">保证金</div>
            <div class="e-table" style="min-height: auto">
                            <el-table
                                :data="tableData"
                                border
                                style="width: 100%"
                                @cell-mouse-enter="cellMouseEnter"
                                @cell-mouse-leave="cellMouseLeave"
                                :cell-class-name="cellClsNm"
                            >
                                <el-table-column prop="a1" label="保证金名称" > </el-table-column>
                                <el-table-column prop="a" label="暂扣保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="b" label="返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="c" label="截止上期末已返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="d" label="截止本期末已返还保证金(元)" width="250"> </el-table-column>
                                <el-table-column prop="d" label="截止本期末未返还保证金(元)" width="250"> </el-table-column>
                            </el-table>
            </div>

          </div> -->

          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
            <attach-comp
              :relationId="attachId"
              bucketName="turnover"
            />
          </div>
          <!-- {{webData}} -->

          <!-- 审核历史 -->
          <div id="auditHistoryCon" class="con">
            <div class="tabs-title" id="auditHistory">审核历史</div>
            <div class="e-table">
                             <ComAuditHistoryIndex :billType="1023" :tableData="shenheArr" @getAuditHistory="getauditHistory" />
                        </div>
          </div>

        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
           <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>
            <!-- <el-button
            v-if="was == 'add' || zhuangtai == '草稿'"
            type="primary"
            class="btn-blue"
            @click="submitCommit"
            size="small"
            >保存并提交</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="submit"
                size="small"
                >保存</el-button
            >
            <el-button
                type="primary"
                class="btn-blue"
                @click="guanbi"
                size="small"
                >关闭</el-button
            >

            <el-button
                v-if="zhuangtai == '审核中' "
                type="primary"
                class="btn-delete"
                @click="nullify"
                size="small"
                >作废</el-button
            > -->
            <exaButtons :auditState="auditState" @exas="exas"  :state="formData.state - 0" :founderId="formData.founderId"></exaButtons>
            <!-- <ComExaButtons :auditState="auditState" @exas="exas" v-if="statusLable(formData.planConfiguration.state) !== '已作废'"/> -->
            <el-button size="small" @click="handleClose">取消</el-button>
        </div>

    <!-- <span style="display: none">{{ localPopConfirm }}</span> -->
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import { showPromptPop, showSuccessPop, getUuid } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'

import planRequest from '@/api/turnover/plan.js'
import { selectDataClient, openAppClient } from '@/utils/common'

import auditRequest from '@/api/materialSettlement/transferSettlement.js'

import publicReques from '@/api/materialSettlement/public.js'

import ComAuditHistoryIndex from '@/components/common/exaHistory.vue'
// import historyUpdateTable from '@/components/common/historyUpdateTable'
import exaButtons from '@/components/common/exaButtons'
import { getRmbRate } from '@/api/equip/common.js'

export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        exaButtons
        // historyUpdateTable
    },
    data () {
        return {
            isFontColor: true, //传输财务共享颜色  未传，返回修改 红色   财务共享审核中，已传 绿色
            //我的数据:↓
            shenheArr: [],
            jsmxtable: [],
            wzmxtable: [],
            rulesBase: {
                billNo: [
                    { required: true, message: '结算编号不能为空', trigger: 'change' }
                ],
                orgName: [
                    { required: true, message: '机构不能为空', trigger: 'change' }
                ],
                settlementDate: [
                    { required: true, message: '结算日期不能为空', trigger: 'change' }
                ],
                transferInUnitName: [
                    { required: true, message: '调入机构不能为空', trigger: 'change' }
                ],
                sourceBillNo: [
                    { required: true, message: '源单编号不能为空', trigger: 'change' }
                ],
                transferorName: [
                    { required: true, message: '源单编号不能为空', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '税率不能为空', trigger: 'change' }
                ],

            },
            formData: {
                amount: 0, //结算金额 元
                baseCurAmount: 0, //结算金额 本位币
                baseCurId: '', //本位币id
                baseCurName: '', //本位币名称
                baseCurRate: 0, //本位币汇率
                baseCurTaxAmount: 0, //税额 本位币
                baseCurTotalAmount: 0, //税价合计 本位币
                billId: '', //调拔结算id
                billNo: '', //结算编号
                currency: '', //币种名称
                currencyId: '', //币种id
                easId: '', //财务id
                founderId: '', //创建人id
                founderName: '', //创建人名称
                gmtCreate: '', //创建时间
                gmtModified: '', //更新时间
                isRed: 0, //是否为红单
                nullifyCreated: '', //作废人
                nullifyCreatorId: '', //作废人id
                nullifyDescription: '', //作废描述
                nullifyReason: '', //作废原因
                orgId: '', //机构id
                orgName: '', //机构名称
                receiverId: '', //接收人员id
                receiverName: '', //接收人名称
                redBillId: '', //红单单据id
                redBillNo: '', //红单单据编号
                redBillState: '', //红单状态
                remarks: '', //备注
                rmbAmount: 0, //	结算金额(人民币)
                rmbId: '', //	人民币id
                rmbName: '', //	人民币名称
                rmbRate: 0, //人民币汇率
                rmbTaxAmount: 0,	//税额(人民币)
                rmbTotalAmount: 0,	//税价合计(人民币)
                settlementDate: '',	//结算日期
                sourceBillId: '',	//源单id
                sourceBillNo: '',	//源单编号
                sourceId: '',	//原结算单id
                sourceNumber: '',	//原结算单编号
                taxAmount: 0,	//税额
                taxRate: 0,	//税率
                totalAmount: 0,	//税价合计
                transferInUnitId: '',	//调入机构Id
                transferInUnitName: '',	//调入机构名称
                transferorId: '',	//调拨人员id
                transferorName: '',	//调拨人员名称
            },
            typeArr: [
                { name: '草稿', id: 0 },
                { name: '审核中', id: 1 },
                { name: '共享审核中', id: 9 },
                { name: '已审核', id: 2 },
                { name: '已关闭', id: -1 },
                { name: '已作废', id: 5 },
            ],
            viewList: true,
            paginationInfo: {
                total: 1,
                pageSize: 10,
                currentPage: 0
            },
            query: {
                beginPlanDate: '',
                endPlanDate: '',
                keyword: '',
                limit: 0,
                orgId: '',
                page: 1,
                settlementUnitId: '',
                states: []
            }, //搜索
            searchKey: '', //右上角搜索关键字
            tableData: [], //表格
            //我的数据:↑

            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6087,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            tabsName: 'baseInfo',
            userName: '',
            clickId: 'baseInfo',
            tabsNameChild: '',
            childTabClass: '',
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },

            OrgtableData: [], //申报机构数据
            OrgSonTableData: [], //申报机构子列表
            materialsTableData: [], //物资汇总数据
            auditHistoryList: [], //审核历史
            planSelect: [], //申报机构表格明细选择项
            value: '',
            textarea: '',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            MouseEnterId: 0,
            nullifyParams: {
                // 作废
                billId: this.$route.query.billid,
                billType: '1023',
                nullifyDescription: '',
                nullifyReason: true,
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: ''
            },
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                'amount': null,
                'billId': '',
                'billNo': '',
                'founderId': '',
                'founderName': '',
                'gmtCreate': '',
                'gmtModified': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'operator': '',
                'operatorId': '',
                'orgId': '',
                'orgName': '',
                'remarks': '',
                'sourceBillId': '',
                'sourceBillNo': '',
                'sourceType': null,
                'state': '',
                'summaryDate': '',
                'workId': ''
            },
            objFlag: {
                flag5: false,
            },
            orgId: '', //机构id
            orgName: '', //机构名称
            billId: '',
            isSkip: false, //是否跳转
            show: true, //申报机构子列表
            dtlIds: '', //
            //验证
            rules: {
                summaryDate: [
                    { required: true, message: '请输入汇总日期', trigger: 'blur' },
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'chenge' },
                ],
            },
            materialsNameData: [], //机构汇总表
            createHistoryData: [], //明细修改历史列表
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            webData: '',
            isReviseBaseCurRate: false, //本位币汇率是否可以修改(默认可修改)
        }
    },
    async created () {
        this.auditState = await publicReques.getCurrentUnitInfo({
            billId: this.$route.query.billid,
            billType: '1023'
        })
        this.billId = this.$route.query.billid
        // this.initData()
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.orgId = data.userInfo.orgInfo.orgId

        this.user = JSON.parse(localStorage.getItem('vuex'))
        this.billId = this.$route.query.billid
        this.infouser = publicReques.getCurrentUnitInfo({
            billId: this.$route.query.billid,
            billType: '1023'
        })
        this.formData = await auditRequest.getdatabyid({ id: this.billId })
        this.isReviseBaseCurRate = this.formData.baseCurId == this.formData.currencyId
        let wzmx = await auditRequest.getmingxibyid({ id: this.billId })
        for(let i = 0 ; i < wzmx.length; i++) {
            wzmx[i].uuid = getUuid()
            if( wzmx[i].children.length > 0) {
                for(let j = 0 ; j < wzmx[i].children.length ; j++) {
                    wzmx[i].children[j].uuid = getUuid()
                    // wzmx[i].children[j].billId = data
                    wzmx[i].children[j].jsje = wzmx[i].children[j].amount
                    wzmx[i].children[j].nbjsdj = wzmx[i].children[j].price
                    wzmx[i].children[j].jssl = wzmx[i].children[j].quantity
                }
            }
        }
        this.wzmxtable = wzmx

    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'planDetail',
            // 'fwfy',
            // 'bzj',
            'accessory',
            'auditHistory',
        ]
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //当点击的tab有子tab时做滚动逻辑
            if (this.clickTabFlag && arr.find(x => x === this.clickId)) {
                this.childTabClass = '' //无子tab时清空tab的类名
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    let itemTop
                    let arr
                    if (item instanceof Array) {
                        const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                        arr = item.map((x, i) => {
                            if (i === 0) {
                                return document.getElementById(x).offsetTop
                            } else {
                                return (
                                    document.getElementById(x).offsetTop +
                  prevHeight +
                  document.getElementById(item[0]).offsetTop
                                )
                            }
                        })
                        return arr
                    } else {
                        itemTop = document.getElementById(item).offsetTop
                        return itemTop
                    }
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            let curLocalChild = 1
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                if ($idsTop[i] instanceof Array) {
                    let item = $idsTop[i]
                    for (let lenth = item.length, j = lenth - 1; j >= 1; j--) {
                        let itemChild = $idsTop[i][j]
                        if (scrollTop + 1 >= itemChild) {
                            curLocalChild = j
                            break
                        }
                    }
                    if (scrollTop + 1 >= item[0]) {
                        curLocal = i
                        break
                    }
                } else {
                    let item = $idsTop[i]
                    if (scrollTop + 1 >= item) {
                        curLocal = i
                        break
                    }
                }
            }
            // 设置对应tabName
            if (arr[curLocal] instanceof Array) {
                this.tabsName = arr[curLocal][0]
                this.tabsNameChild = arr[curLocal][curLocalChild]
            } else {
                this.tabsName = arr[curLocal]
            }
            // //动态改变二级选项卡类名
            // arr.forEach((item, index) => {
            //     if (item instanceof Array) {
            //         let tabNavHeight = document.querySelector('.childTab .el-tabs__nav')
            //             ? document.querySelector('.childTab .el-tabs__nav').offsetHeight
            //             : 0
            //         if (scrollTop + 1 >= $idsTop[index + 1] - tabNavHeight) {
            //             this.childTabClass = 'childTab2'
            //         } else if (scrollTop <= $idsTop[index][1]) {
            //             this.childTabClass = ''
            //         } else {
            //             this.childTabClass = 'childTab1'
            //         }
            //     }
            // })
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                let itemTop
                let arr
                if (item instanceof Array) {
                    const prevHeight = document.getElementById(item[0]).offsetHeight //因这里一个选项有两个表格，需获取前一个表格的高度进行计算
                    arr = item.map((x, i) => {
                        if (i === 0) {
                            return document.getElementById(x).offsetTop
                        } else {
                            return (
                                document.getElementById(x).offsetTop +
                prevHeight +
                document.getElementById(item[0]).offsetTop
                            )
                        }
                    })
                    return arr
                } else {
                    itemTop = document.getElementById(item).offsetTop
                    return itemTop
                }
            })
        })
    },
    watch: {
        amount2 (ww1, ww2) {

				 console.log('xinde', ww1, ww2)
            this.formData.taxAmount = (((ww1 - 0) *  (this.formData.taxRate / 100)).toFixed(2)) - 0
        }

    },
    computed: {
        ...mapState({
            options: state => state.contract.ctClassify,
            popConfirm: 'popConfirm',
            popStatus: 'popStatus',
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            state: state => state.equip.equipData.state, //通用流程状态
            shareFrom: state => state.equip.equipData.shareFrom,
        }),
        //my 计算属性 ↓
        amount2 () {
            let num = 0
            for(let i = 0 ;  i < this.wzmxtable.length ; i++) {
                if(this.wzmxtable[i].children.length > 0) {
                    for(let j = 0 ; j < this.wzmxtable[i].children.length ; j++) {
                        const item = this.wzmxtable[i].children[j]
                        let jine =  0
                        if(item.jsje) {
                            jine = item.jsje
                        }
                        num += (jine - 0)
                    }
                }
            }
            return num.toFixed(2) * 1
        },
        shuie () {
            return ((this.amount2 * (this.formData.taxRate / 100)).toFixed(2)) - 0
        },
        shuijiaheji () {
            const target =  ((this.amount2 - 0) + (this.formData.taxAmount - 0)) - 0
            return target.toFixed(2) * 1
        },
        jisuanjinebenweibi () {
            console.log(this.formData.baseCurRate, '这是税率')
            return (this.amount2 * this.formData.baseCurRate) - 0
        },
        // my 计算属性 ↑
        // localPopConfirm () {
        //     if (this.popConfirm) {
        //         switch (this.popStatus) {
        //         case 'prompt':
        //             this.delData()
        //             break
        //         case 'success':
        //             if (this.isSkip) this.handleClose()
        //             break
        //         }
        //         this.setPopConfirm(false)
        //     }
        //     return this.popConfirm
        // },
        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value == param)

                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        //传输财务共享
        shareLable () {
            return param=> {
                const state = this.shareFrom
                const obj = state.find(x=>x.value === param)
                return (obj ?  obj.label :  '')
            }
        },
    },
    methods: {
        ...mapMutations(['setPopConfirm', 'setSelectedInfo', 'setHistoryTableData', 'setAuditParams']),
        //my ↓
        guanbi () {
            this.$router.push('/transferSettlementlist')
        },
        async exas (arg) {
            if (arg === 'submit') {
                console.log('1') // 保存所有数据
                await this.submit()
            } else if (arg === 'submitCommit') {
                console.log('2') // 保存并提交
                await this.submitCommit()
            } else if (arg === 'audit') {
                console.log('3') // 审核
                await this.shenhe()
            } else if (arg === 'undoAudit') {
                await this.nullify() // 撤销审核
            } else if (arg === 'nullify') {
                console.log('555') // 作废(
                this.zuofei()
            } else if (arg === 'deleteData') {
                console.log('6') // 删除
                await this.shanchu1()
            }
        },
        async shanchu1 () {
            this.clientPop('info', '确认删除这条数据吗？此操作无法逆转!', this.deljkk111, null, this.deljkk5)
        },
        async deljkk111 () {
            await auditRequest.deljiesuan({ id: this.billId })
            this.clientPop('suc', '删除成功')
            this.$router.replace('/transferSettlementlist')
        },
        zuofei () {
            this.setAuditParams(this.nullifyParams)
            // 客户端弹窗弹出本地页面
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                // this.setSelectedInfo(auditParams)
                // // 客户端弹窗预览结果
                // // 参数依次为: 打开页面地址、标题、回调函数
                // openAppClient('/showSelectedData', '选择结果', function () {
                //     // alert('关闭后回调')
                // })

                publicReques
                    .zuofei(auditParams)
                    .then(() => {
                        this.clientPop('suc', '作废成功', this.handleClose)
                    })

            })
        },
        async shenhe () {
            openAppClient('/exaDialog', '填写审核意见',  ()=> {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                // 将审核意见赋值给参数传给后端
                publicReques.goaudit({
                    billId: this.billId,
                    billType: '1023',
                    isPass: auditParams.isPass,
                    isShareInAudit: false,
                    opinion: auditParams.opinion

                }).then(() => {
                    this.clientPop('suc', '审核成功')
                    this.$router.replace('/transferSettlementlist')
                }).catch(()=>{
                    this.clientPop('suc', '审核失败')
                })

            })
        },
        async nullify () {
            //撤回
            console.log('撤回')
            await publicReques.goBack({ billId: this.billId, billType: '1023' })
            this.clientPop('suc', '撤回成功')
            this.$router.replace('/transferSettlementlist')
        },

        mxchang (row, type) {
            console.log(row, 'row')
            console.log(type)
            //价差 difference
            //内部结算单价 price
            //实际结算单价 actualPurchasePrice
            //jssl 结算数量
            //nbjsdj 内部  actualPurchasePrice实际
            row.difference = row.jssl || 0 * (row.nbjsdj || 0 - row.actualPurchasePrice || 0)
            if(type == 'jssl') {
                if((row.jssl - 0) >= 0) {
                    if(row.jsje && row.jsje !== 0) {
                        row.nbjsdj = (row.jsje / row.jssl).toFixed(2)
                    }
                }
                //验证结算数量是否大于未结算数量
                if(row.jssl > row.unsettledQuantity) {
                    row.jssl = row.unsettledQuantity
                    this.$message.error('未结算数量不可大于结算数量')
                }else {
                    row.jssl = Number(row.jssl)
                }
            }else{
                if((row.jsje - 0) >= 0) {
                    for(let z = 0 ; z < this.wzmxtable.length; z++) {
                        let item =  this.wzmxtable[z]
                        let num2 = 0
                        console.log('item', item)
                        if(item.children.length > 0) {
                            for(let x = 0 ; x < item.children.length ; x++) {
                                const item2 = item.children[x]
                                num2 += (item2.jsje - 0)
                            }
                        }
                        item.materialName = '小计:' + num2
                    }
                    if(row.jssl && row.jssl !== 0) {
                        row.nbjsdj = (row.jsje / row.jssl).toFixed(2)
                    }
                }
            }
        },
        //审核历史
        async getauditHistory () {
            if(this.billId !== '') {
                console.log('进来咯 进来咯 进来咯 进来咯')
                const data = await publicReques.getauditHistory({
                    'billId': this.billId,
                    'billType': 1023,
                    'freeNextUnitIndex': 0,
                    'freeNextUser': '',
                    'isPass': true,
                    'isShareInAudit': true,
                    'opinion': ''
                })
                this.shenheArr = data
            }
        },
        //选择调拨单 tps
        async xzdbd () {
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/material/internalAllocation/listSettleableDtlsForSelect', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                //  this.user.userInfo.orgInfo.orgId
                InitParamsStr: '0',    // 接口参数(name为模拟参数)
                Title: '选择机构用户' // 标题
            }).then(val1 => {
                if(val1.length > 0) {
                    this.father = {}
                    for(let i = 0 ; i < val1.length; i++) {
                        if(val1[i].parentId != '0' || val1[i].parentId != 0) {
                            this.father = val1[i]
                            break
                        }
                    }
                }
                let res = this.father //默认用户选择了第一个 模拟弹窗
                this.$set(this.formData, 'sourceBillId', res.billId)
                this.$set(this.formData, 'sourceBillNo', res.billNo)
                this.$set(this.formData, 'transferInUnitId', res.transferInUnitId)
                this.$set(this.formData, 'transferInUnitName', res.transferInUnitName)
                this.$set(this.formData, 'receiverId', res.pickingPersonnelId)
                this.$set(this.formData, 'receiverName', res.pickingPersonnelName)
                this.$set(this.formData, 'transferorId', res.issuingPersonnelId)
                this.$set(this.formData, 'transferorName', res.issuingPersonnelName)
                this.$set(this.formData, 'currency', res.currency)
                this.$set(this.formData, 'currencyId', res.currencyId)
                this.$set(this.formData, 'baseCurId', res.baseCurId)
                this.$set(this.formData, 'baseCurName', res.baseCurName)
                //本位币汇率是否可以修改
                this.isReviseBaseCurRate = res.baseCurId == res.currencyId
                this.$set(this.formData, 'baseCurRate', 1)
                //获取人名币汇率
                const obj = {
                    currency: res.currencyId,
                    orgId: this.formData.orgId
                }
                getRmbRate(obj)
                    .then(res=>{
                        this.$set(this.formData, 'rmbRate', res.rate)
                    })
                res = []
                for(let i = 0 ; i < val1.length ; i++) {
                    if(val1[i].parentId != '0' && val1[i].parentId != 0) {
                        res.push(val1[i])
                    }
                }
                const mapObj = {}
                let arr = []
                res.forEach(e => {
                    const children = []
                    e.materialClassNameArr = e.materialClassName.split('/')
                    e.materialClassIdArr = e.materialClassId.split('/')
                    let obj
                    const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                    const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                    if (!mapObj[topClassId]) {
                        obj = {
                            topClassId,
                            topClassName,
                            customId: topClassId,
                            // materialClassId: topClassId,
                            // materialClassName: topClassName,
                            uuid: getUuid(),
                            totalAmount: null,
                            totalQuantity: null,
                        }
                        //这里需要改成push多个对象   还没改
                        arr.push(obj)
                        mapObj[topClassId] = obj
                    } else {
                        obj = mapObj[topClassId]
                    }
                    children.push({
                        uuid: getUuid(),
                        billId: this.billId || '',
                        billNo: this.basicFormData.billNo || '',
                        customId: getUuid(),
                        warehouse: e.warehouse,
                        unsettledQuantity: e.unsettledQuantity, //未结算数量
                        acceptedQuantity: null, //已验收数量
                        changeType: 1,
                        dtlId: '', //加工收料明细id
                        materialClassId: topClassId, //物资类别id(
                        materialClassName: topClassName, //物资类别名称
                        materialId: e.listId, //物资id
                        materialName: e.materialName, //物资名称
                        actualPurchasePrice: e.price, //单价
                        quantity: e.quantity, //数量
                        sourceDtlId: '', //源单明细id
                        spec: e.specificationModel, //规格型号
                        texture: e.textureOfMaterial, //材质
                        unit: e.unit, //计量单位
                        warehouseId: '', //仓库id
                        warehouseName: '', //仓库名称
                        settlementUnit: 0, //结算数量
                        amount: 0, //金额
                        difference: 0,
                        jssl: e.unsettledQuantity // 结算数量
                    })
                    obj.children = !obj.children
                        ? children
                        : obj.children.concat(children)
                    obj.children = this.uniqueArray(obj.children, 'customId')
                })
                this.wzmxtable = arr

            })
        },
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        chakanyd () {
            console.log('查看原单')
        },
        //my ↑
        initData () {
            this.getCurrentUnitInfo()
            this.getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId()
            this.getBasicData()
            this.getTurnoverCentralizedPurchaseSummaryGetSummarySetting() //回去物资汇总明细
        },
        //获取按钮状态
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetAgencyListByBillId () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAgencyListByBillId(this.billId).then(res=>{
                this.OrgtableData = res
                // this.rollUp(res)
            })
        },

        //根据周材集采汇总id查询申报机构
        getTurnoverCentralizedPurchaseSummaryGetSummarySetting () {
            planRequest.turnoverCentralizedPurchaseSummaryGetSummarySetting(this.billId).then(res=>{
                console.log(res, '当前打印')
                // this.OrgtableData = res
                this.notSetData = JSON.parse(JSON.stringify(res)) //没去重之前的数据
                //去重
                let children = []
                res.forEach(item=>{
                    item.children.forEach(a=>{
                        children.push(a)
                    })
                })
                var result = []
                var obj = {}
                for (var i = 0; i < children.length; i++) {
                    if ( children[i].materialId in obj) {
                        // 相同时肯定不push
                        if (obj[children[i].materialId] !== children[i].texture) {
                            // 不相同时，判断是否是 '' 和 null，如果是，则表示重复
                            if (!(!obj[children[i].materialId] && !children[i].texture)) {
                                // 当都不是 '' 和 null 时，才表示不重复，此时才push
                                result.push(children[i])
                            }
                        }
                    } else {
                        obj[children[i].materialId] = children[i].texture
                        result.push(children[i])
                    }
                    // obj[children[i].amount] = 1

                }
                res.forEach(item=>{
                    item.uuid = getUuid()

                    item.materialClassName = item.topClassName
                    item.children = result
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.parentId = item.uuid
                    })
                })
                console.log(result, 'datadata')
                this.materialsTableData = res
            })
        },

        //向上汇总
        rollUp (res) {
            res.forEach(item=>{ //拿到 数据 汇总计划金额
                this.basicFormData.amount += item.totalAmount
            })
        },
        shanchumx () {
            console.log(this.wzlbTableData)
            //先判断是 选择的 自己还是
            this.clientPop('info', '确认删除这' + this.planSelect.length + '条数据吗？', this.deljkk1, null, this.deljkk5)
        },
        deljkk1 () {
            console.log(this.wzmxtable)
            for(let i = 0 ; i < this.wzmxtable.length; i++) {
                for(let j = 0; j < this.wzmxtable[i].children.length ; j++) {
                    for(let h = 0 ; h < this.planSelect.length ; h++) {
                        if(this.wzmxtable[i].children[j].id ==  this.planSelect[h].id) {
                            this.wzmxtable[i].children[j].changeType = -1
                        }
                    }
                }
            }
            this.$refs.multipleTable1.clearSelection()
        },
        deljkk5 () {
            console.log('没事')
        },
        //点击图标的时候 获取历史记录
        clickIcon (dtlId, column) {
            this.setHistoryTableData([])
            alert(dtlId)
            planRequest
                .turnoverAnnualDemandPlanGetHistoryList(
                    dtlId,
                    column,
                    this.auditParams.billType
                )
                .then(res => {
                    this.historyTableData = res
                    this.setHistoryTableData(res)
                })
                .catch(e => {
                    alert(e.message)
                })
        },
        // 编辑的时候造历史修改数据结构
        createHistory (row, e) {
            if (row.dtlId) {
                this.createHistoryData.push({
                    historyId: '',
                    modifedName: '',
                    modifiedDate: '',
                    modifiedId: '',
                    opinion: '',
                    sourceId: row.dtlId,
                    sourceValue: 0,
                    updateColumn: e, //修改字段
                    updatedValue: row[e] //修改后的值
                })
            }
        },
        /**
         * 下边几个按钮
         */
        async thesubimt1 () {
            const data = await auditRequest.setdiaobajiesuan({ ...this.formData,  totalAmount: this.shuijiaheji, amount: this.amount2, baseCurAmount: this.jisuanjinebenweibi })
            console.log(data, 'data')
            // this.
            console.log()
            for(let i = 0 ; i < this.wzmxtable.length ; i++) {
                if(this.wzmxtable[i].children.length > 0) {
                    for(let j = 0 ; j < this.wzmxtable[i].children.length ; j++) {
                        let item = this.wzmxtable[i].children[j]
                        if(item.changeType != -1) {
                            // item.billId = data
                            if(item.changeType === null) {
                                item.amount = item.jsje
                                item.price = item.nbjsdj
                                item.quantity = item.jssl
                                item.changeType = 2
                            }else{
                                item.amount = item.jsje
                                item.price = item.nbjsdj
                                item.quantity = item.jssl
                                item.changeType = 1
                            }
                        }
                    }
                }
            }
            await auditRequest.updatemingxixinxi(this.wzmxtable)
            this.clientPop('suc', '保存成功')
            location.reload()
            // this.$router.replace('/transferSettlementlist')
        },
        //保存按钮
        submit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.thesubimt1()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })

        },
        async thesubimt2 () {
            const data = await auditRequest.setdiaobajiesuan({ ...this.formData, totalAmount: this.shuijiaheji, amount: this.amount2, baseCurAmount: this.jisuanjinebenweibi })
            console.log(data, 'data')
            // this.
            console.log()
            for(let i = 0 ; i < this.wzmxtable.length ; i++) {
                if(this.wzmxtable[i].children.length > 0) {
                    for(let j = 0 ; j < this.wzmxtable[i].children.length ; j++) {
                        let item = this.wzmxtable[i].children[j]
                        if(item.changeType != -1) {
                            // item.billId = data
                            if(item.changeType === null) {
                                item.amount = item.jsje
                                item.price = item.nbjsdj
                                item.quantity = item.jssl
                                item.changeType = 2
                            }else{
                                item.amount = item.jsje
                                item.price = item.nbjsdj
                                item.quantity = item.jssl
                                item.changeType = 1
                            }
                        }
                    }
                }
            }
            await auditRequest.updatemingxixinxi(this.wzmxtable)
            await publicReques.commitexamine({ billId: this.billId,	billType: '1023' })
            this.clientPop('suc', '提交审核成功')
            this.$router.replace('/transferSettlementlist')
        },
        // 保存并提交
        submitCommit () {
            this.$refs.rulesBase.validate(valid => {
                console.log('gg', valid)
                if (valid) {
                    this.thesubimt2()
                } else {
                    console.log('error submit!!')
                    return false
                }
            })
        },
        //计划明细非空验证
        verifyTable () {

            this.errorMsg = []
            if(this.OrgtableData.length > 0) {
                this.OrgtableData.forEach((n, index)=>{
                    if(n.dtls) {
                        n.dtls.forEach(v=>{
                            v.children.forEach(item=>{
                                if(item.changeType !== -1) {
                                    if (item.approvalQuantity == '' || item.approvalQuantity == null) {
                                        let str = `请填写第 ${index + 1} 行的核准数量`
                                        this.errorMsg.push(str)
                                    }
                                    if (item.approvalPrice == '' || item.approvalPrice == null) {
                                        let str = `请填写第 ${index + 1} 行的核准单价`
                                        this.errorMsg.push(str)
                                    }

                                }
                            })
                        })
                    }

                })
            }

            if(this.errorMsg.length > 0) {
                this.isErrorMsg = true

            }else{
                this.isErrorMsg = false

            }

        },

        //把子列表的数据合并到this.OrgtableData的children
        DoMaterialsTableData () {
            this.OrgtableData.forEach(item=>{
                item.changeType = 1
                item.billId = this.billId

            })
        },

        //点击选择 选择申报单位 获取申报机构
        selectUnit () {
            planRequest.turnoverCentralizedPurchaseSummaryGetAgencyListByOrgId(['1505122036192309249'])
                .then(res => {
                    this.OrgtableData = res
                    this.DoMaterialsTableData() //给数据造billid 和 chengetype
                    this.isCollect = true
                })
        },
        //点击申报单位列表点击编号显示对应子列表
        tableDbShow (row, column) {
            row.dtls = []
            if(column.label === '年度需用计划编号') {
                if(row.changeType == 1) {
                    planRequest.turnoverCentralizedPurchaseSummaryGetAllMaterial(row.annualDemandPlanBillId).then(res=>{
                        this.OrgSonTableData = res
                        this.OrgSonTableData.forEach(item=>{
                            item.changeType = 1
                            item.uuid =  getUuid()
                            item.materialClassName = item.topClassName

                            item.children.forEach(v=>{
                                v.changeType = 1
                                v.parentId = item.uuid
                                v.uuid =  getUuid()
                            })
                            row.dtls.push(item)
                        })
                    })
                }else {
                    planRequest.turnoverCentralizedPurchaseSummaryGetMaterial(row.dtlId).then(res=>{
                        this.OrgSonTableData = res
                        this.OrgSonTableData.forEach(item=>{
                            item.uuid =  getUuid()
                            item.materialClassName = item.topClassName
                            row.dtls.push(item)
                            item.children.forEach(v=>{
                                v.changeType = 2
                                v.parentId = item.uuid
                                v.uuid =  getUuid()
                            })
                        })
                    })
                }

            }

        },
        // 点击子表的选择明细
        selectDetails () {
            console.log('选择明细')
        },
        //点击集中采购单位 选择单位
        clickPurchasingUnit (row) {
            selectDataClient()
            // 弹窗选择数据
            selectDataClient({
                SelectServiceToken: '/hr/org/getChildrenOrg', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id
                Title: '选择全集团组织机构数据', // 标题
                InitParamsStr: JSON.stringify({ orgId: this.basicFormData.orgId }), //参数

            }).then(val => {
                const orgData = val[0] //获取客户端返回的数据
                row.purchasingUnitId = orgData.orgId
                row.purchasingUnitName = orgData.orgName
                row.changeType === 1 ? this.count_(row, 1) : this.count_(row, 2) //判断当前的状态是新增还是修改
                // 保存用户选择返回数据到store
                this.setSelectedInfo(val)
                // 客户端弹窗预览结果
                // 参数依次为: 打开页面地址、标题、回调函数
                // openAppClient('/showSelectedData', '选择结果', function () {
                //     alert('关闭后回调')

                // })
            })
        },
        //点击物资汇总的物资名称，汇总物资下的所有机构
        showA (row) {
            console.log(row, 'row')
            console.log(this.notSetData, 'this.notSetData')
            this.materialsNameData = []
            this.notSetData.forEach(item=>{
                item.children.forEach(b=>{
                    if( row.materialId === b.materialId) {
                        // const obj = {
                        //     orgName: item.orgName,
                        //     materialName: b.materialName,
                        //     spec: b.spec,
                        //     unit: b.unit,
                        //     texture: b.texture,
                        //     planQuantity: b.planQuantity,
                        //     marketPrice: '',
                        //     amount: b.amount
                        // }
                        // this.materialsNameData = []
                        this.materialsNameData.push(b)
                    }
                })
            })

        },
        //申报机构汇总-删除 申报机构汇总表格明细
        deleteMaterials () {
            if (this.planSelect.length > 0) {
                this.OrgtableData.forEach(v=>{
                    this.planSelect.forEach(item=>{
                        if(item.dtlId && item.dtlId === v.dtlId) {
                            v.changeType = -1
                        }
                    })

                })
            }
            if (this.planSelect.length > 0) {
                this.planSelect.forEach(item => {
                    if (item.dtlId) {
                        const newArr = []
                        newArr.push(item)
                        newArr.forEach(item => {
                            this.$set(item, 'changeType', -1)
                        })

                        // this.$refs.multipleTable.clearSelection()
                    } else {
                        const localArr = []
                        localArr.push(item)
                        for (
                            let i = this.OrgtableData.length;
                            i > 0;
                            i--
                        ) {
                            for (let j = 0; j < localArr.length; j++) {
                                if (
                                    this.OrgtableData[i - 1] ===
                                    localArr[j]
                                ) {
                                    this.OrgtableData.splice(i - 1, 1)
                                }
                            }
                        }
                        // this.$refs.multipleTable.clearSelection()
                    }
                })
            }
            console.log(this.OrgtableData)

        },

        //监听明细 机构汇总表格 数据input事件 判断用户是否修改  ，计算金额
        countInput (row) {
            row.changeType === 1 ? this.count_(row, 1) : this.count_(row, 2)
            console.log(this.materialsTableData, '物资汇总')
        },
        // 汇总逻辑
        count_ (row, num) {
            row.changeType = num
            this.basicFormData.amount = null
            row.approvalAmount =  row.approvalQuantity * row.approvalPrice
            this.OrgtableData.forEach(item =>{
                console.log(item, '逻辑汇总')
                item.changeType = num
                this.basicFormData.amount += item.totalAmount = row.approvalAmount  //把汇总的金额给父级 方便汇总计算
                if(item.children) {
                    item.children.forEach(i=>{
                        i.changeType = num
                    })
                }
            })
        },
        //申报机构汇总-明细子列表删除按钮
        deleteEle (row) {

            row.changeType = -1
            this.OrgtableData.forEach(item =>{
                item.changeType = 2
                if(item.dtls) {
                    item.dtls.forEach(v=>{
                        if(v.children) {
                            const data =  v.children.find(i=>{
                                return i.dtlId === row.dtlId
                            })
                            data.changeType = -1

                        }
                    })
                }
            })

        },
        //获取集采汇总id获取基本信息
        getBasicData () {
            planRequest.turnoverCentralizedPurchaseSummaryFindById(this.billId)
                .then(res => {
                    this.basicFormData = res
                })
        },
        //删除提示框
        ctDelete () {
            showPromptPop('确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。')
        },
        //根据集采汇总id删除单据
        delData () {
            planRequest.turnoverCentralizedPurchaseSummaryDelete(this.billId)
                .then(res => {
                    if (res.code == 200) {
                        showSuccessPop('删除成功！')
                        this.isSkip = true
                    }
                    this.$router.push('./revolveCollectList')
                })
        },
        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },
        //申报机构删除逻辑
        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        //获取用户在 汇总明细-申报机构汇总 表格的已选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //取消
        handleClose () {
            // this.dialogVisible = false
            this.$router.replace('/transferSettlementlist')
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },
        isnumshow (num) {
            console.log('num', num)
        },
        //查看源单
        goTocontract () {
            openAppClient(
                `/interiorAllotEetails?billid=${this.formData.sourceBillId}&isview=true`, '查看物资调拨单'
            )
        },
    },
}
</script>

<style lang="scss" scoped>
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
}
::v-deep.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
.childTab {
  ::v-deep .el-tabs__header {
    position: absolute !important;
  }
  ::v-deep .el-tabs__content {
    padding: 0 0 0 20px !important;
  }
}
.childTab1 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: fixed;
        top: 0;
        width: 190px;
      }
    }
  }
}
.childTab2 {
  ::v-deep .el-tabs__header {
    position: absolute !important;
    .el-tabs__nav-scroll {
      position: relative;
      .el-tabs__nav {
        position: absolute;
        bottom: 0;
        width: 100%;
      }
    }
  }
}
</style>

